#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right)
    {
    }
};

class Solution 
{
public:
    TreeNode* convertBST(TreeNode* root) 
    {
        if(root == nullptr)
        {
            return nullptr;
        }
        stack<pair<TreeNode * , bool>> st;
        st.push(make_pair(root, false));
        int sum = 0;
        while (!st.empty())
        {
            TreeNode * node = st.top().first;
            bool visited = st.top().second;
            st.pop();
            if(visited)
            {
                sum += node->val;
                node->val = sum;
                continue;
            }
            if(node->left != nullptr)
            {
                st.push(make_pair(node->left, false));
            }
            st.push(make_pair(node, true));
            if(node->right != nullptr)
            {
                st.push(make_pair(node->right, false));
            }
        }
        return root;
    }
};

// 辅助函数：从数组构建二叉搜索树（层序遍历方式，-1表示null）
TreeNode *buildTreeFromArray(vector<int> &arr)
{
    if (arr.empty() || arr[0] == -1) return nullptr;

    TreeNode *root = new TreeNode(arr[0]);
    queue<TreeNode *> q;
    q.push(root);

    int i = 1;
    while (!q.empty() && i < arr.size())
    {
        TreeNode *node = q.front();
        q.pop();

        // 左子节点
        if (i < arr.size() && arr[i] != -1)
        {
            node->left = new TreeNode(arr[i]);
            q.push(node->left);
        }
        i++;

        // 右子节点
        if (i < arr.size() && arr[i] != -1)
        {
            node->right = new TreeNode(arr[i]);
            q.push(node->right);
        }
        i++;
    }

    return root;
}

// 辅助函数：层序遍历打印二叉树
void printTree(TreeNode *root)
{
    if (!root)
    {
        cout << "[]" << endl;
        return;
    }

    queue<TreeNode *> q;
    q.push(root);
    vector<string> result;

    while (!q.empty())
    {
        TreeNode *node = q.front();
        q.pop();

        if (node)
        {
            result.push_back(to_string(node->val));
            q.push(node->left);
            q.push(node->right);
        } else
        {
            result.push_back("null");
        }
    }

    // 移除末尾的null
    while (!result.empty() && result.back() == "null")
    {
        result.pop_back();
    }

    cout << "[";
    for (int i = 0; i < result.size(); i++)
    {
        cout << result[i];
        if (i < result.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

// 辅助函数：中序遍历验证BST性质
void inorderTraversal(TreeNode *root, vector<int> &result)
{
    if (!root) return;
    inorderTraversal(root->left, result);
    result.push_back(root->val);
    inorderTraversal(root->right, result);
}

// 辅助函数：验证转换后的树是否满足Greater Sum Tree性质
bool isValidGST(TreeNode *root, vector<int> &originalInorder)
{
    vector<int> gstInorder;
    inorderTraversal(root, gstInorder);
    
    if (gstInorder.size() != originalInorder.size()) return false;
    
    // 计算每个节点应该的值（原值 + 所有大于它的值的和）
    for (int i = 0; i < originalInorder.size(); i++)
    {
        int expectedValue = originalInorder[i];
        for (int j = i + 1; j < originalInorder.size(); j++)
        {
            expectedValue += originalInorder[j];
        }
        if (gstInorder[i] != expectedValue) return false;
    }
    
    return true;
}

// 辅助函数：打印vector
void printVector(const vector<int> &vec)
{
    cout << "[";
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i];
        if (i < vec.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

// 辅助函数：释放二叉树内存
void deleteTree(TreeNode *root)
{
    if (!root) return;
    deleteTree(root->left);
    deleteTree(root->right);
    delete root;
}

int main()
{
    Solution solution;

    cout << "=== LeetCode 538. 把二叉搜索树转换为累加树 测试案例 ===" << endl << endl;

    // 测试案例1：题目示例1
    cout << "测试案例1：" << endl;
    vector<int> tree1 = {4, 1, 6, 0, 2, 5, 7, -1, -1, -1, 3, -1, -1, -1, 8};
    TreeNode *root1 = buildTreeFromArray(tree1);
    
    // 保存原始中序遍历结果用于验证
    vector<int> originalInorder1;
    inorderTraversal(root1, originalInorder1);

    cout << "输入: root = ";
    printTree(root1);
    cout << "原始中序遍历: ";
    printVector(originalInorder1);

    TreeNode *result1 = solution.convertBST(root1);
    cout << "输出: ";
    printTree(result1);
    cout << "验证GST性质: " << (isValidGST(result1, originalInorder1) ? "通过" : "失败") << endl << endl;

    // 测试案例2：题目示例2
    cout << "测试案例2：" << endl;
    vector<int> tree2 = {0, -1, 1};
    TreeNode *root2 = buildTreeFromArray(tree2);
    
    vector<int> originalInorder2;
    inorderTraversal(root2, originalInorder2);

    cout << "输入: root = ";
    printTree(root2);
    cout << "原始中序遍历: ";
    printVector(originalInorder2);

    TreeNode *result2 = solution.convertBST(root2);
    cout << "输出: ";
    printTree(result2);
    cout << "验证GST性质: " << (isValidGST(result2, originalInorder2) ? "通过" : "失败") << endl << endl;

    // 测试案例3：题目示例3（空树）
    cout << "测试案例3（空树）：" << endl;
    TreeNode *root3 = nullptr;

    cout << "输入: root = ";
    printTree(root3);

    TreeNode *result3 = solution.convertBST(root3);
    cout << "输出: ";
    printTree(result3);
    cout << "验证: " << (result3 == nullptr ? "通过" : "失败") << endl << endl;

    // 测试案例4：单节点树
    cout << "测试案例4（单节点树）：" << endl;
    vector<int> tree4 = {1};
    TreeNode *root4 = buildTreeFromArray(tree4);
    
    vector<int> originalInorder4;
    inorderTraversal(root4, originalInorder4);

    cout << "输入: root = ";
    printTree(root4);
    cout << "原始中序遍历: ";
    printVector(originalInorder4);

    TreeNode *result4 = solution.convertBST(root4);
    cout << "输出: ";
    printTree(result4);
    cout << "验证GST性质: " << (isValidGST(result4, originalInorder4) ? "通过" : "失败") << endl << endl;

    // 测试案例5：简单的三节点BST
    cout << "测试案例5（简单的三节点BST）：" << endl;
    vector<int> tree5 = {2, 1, 3};
    TreeNode *root5 = buildTreeFromArray(tree5);
    
    vector<int> originalInorder5;
    inorderTraversal(root5, originalInorder5);

    cout << "输入: root = ";
    printTree(root5);
    cout << "原始中序遍历: ";
    printVector(originalInorder5);

    TreeNode *result5 = solution.convertBST(root5);
    cout << "输出: ";
    printTree(result5);
    cout << "验证GST性质: " << (isValidGST(result5, originalInorder5) ? "通过" : "失败") << endl << endl;

    // 测试案例6：只有右子树的BST
    cout << "测试案例6（只有右子树）：" << endl;
    vector<int> tree6 = {1, -1, 2, -1, -1, -1, 3};
    TreeNode *root6 = buildTreeFromArray(tree6);
    
    vector<int> originalInorder6;
    inorderTraversal(root6, originalInorder6);

    cout << "输入: root = ";
    printTree(root6);
    cout << "原始中序遍历: ";
    printVector(originalInorder6);

    TreeNode *result6 = solution.convertBST(root6);
    cout << "输出: ";
    printTree(result6);
    cout << "验证GST性质: " << (isValidGST(result6, originalInorder6) ? "通过" : "失败") << endl << endl;

    // 测试案例7：包含负数的BST
    cout << "测试案例7（包含负数）：" << endl;
    vector<int> tree7 = {0, -2, 2, -3, -1, 1, 3};
    TreeNode *root7 = buildTreeFromArray(tree7);
    
    vector<int> originalInorder7;
    inorderTraversal(root7, originalInorder7);

    cout << "输入: root = ";
    printTree(root7);
    cout << "原始中序遍历: ";
    printVector(originalInorder7);

    TreeNode *result7 = solution.convertBST(root7);
    cout << "输出: ";
    printTree(result7);
    cout << "验证GST性质: " << (isValidGST(result7, originalInorder7) ? "通过" : "失败") << endl << endl;

    // 清理内存
    deleteTree(result1);
    deleteTree(result2);
    deleteTree(result3);
    deleteTree(result4);
    deleteTree(result5);
    deleteTree(result6);
    deleteTree(result7);

    cout << "所有测试案例执行完毕！" << endl;

    return 0;
}